import React, { useEffect, useState } from 'react';
import { connect, history, KeepAlive } from 'umi';
import type { ConnectState } from '@/models/connect';
import Header from '@/components/GlobalHeader';
import Menu from '@/components/Menu';
import { Tabs } from 'antd';
import './BasicLayout.less';

const TabPane = Tabs.TabPane;

const BasicLayout: React.FC = (props: any) => {
  const {
    location,
    route: { routes },
    menuslider,
    menuslider: { systemMenuBar },
  } = props;
  const [activeKey, setActiveKey] = useState('/');

  // 路由变更更新右侧tab选中项
  // useEffect(() => {
  //   if (location.pathname !== activeKey) {
  //     setActiveKey(location.pathname);
  //   }
  // }, [location.pathname]);

  useEffect(() => {
    // location.pathname = '/appopera/operationaldata';
    if (location.pathname == '/') return;
    if (location.pathname && activeKey == '/' && !systemMenuBar.length) {
      const routeArr = routes.filter((route: any) =>
        location.pathname.startsWith(
          route.path.replace(':staf', '').replace('/:sys', ''),
        ),
      );
      if (routeArr.length) {
        menuClick({ ...routeArr[0], path: location.pathname });
        setActiveKey(location.pathname);
      } else {
        history.push('/');
      }
    }
    if (location.pathname !== activeKey) {
      setActiveKey(location.pathname);
    }
  }, [location.pathname, activeKey]);

  const jumpTo = (path: string) => {
    history.push(path);
  };

  const menuClick = (data: any) => {
    let path1: any = data.path;
    const menuNavBarCopy = JSON.parse(JSON.stringify(systemMenuBar));
    const index = menuNavBarCopy.findIndex((item: any) => item.path === path1);
    if (index < 0) {
      props.dispatch({
        type: 'menuslider/saveSystemMenuBar',
        payload: [...menuNavBarCopy, data],
      });
    }
    setActiveKey(path1);
    jumpTo(path1);
  };

  const closeMenu = (targetKey: string) => {
    event.stopPropagation();
    let systemMenuBar = JSON.parse(JSON.stringify(props.systemMenuBar));
    let menuBar = systemMenuBar.filter((item: any) => item.path !== targetKey);
    if (menuBar.length === 0) {
      history.push('/');
    } else {
      // 剩余跳转删除位置的前一个位置
      history.push(menuBar[menuBar.length - 1].path);
    }
    props.dispatch({
      type: 'menuslider/saveSystemMenuBar',
      payload: menuBar,
    });
  };

  return (
    <div className="basiclayout">
      <div className="basHeader">
        <Header />
      </div>
      <div className="basContent">
        <div className="sidenav">
          <Menu menuClick={menuClick} />
        </div>
        <div className="contRight">
          {systemMenuBar.length > 0 ? (
            <Tabs
              onEdit={closeMenu}
              activeKey={activeKey}
              hideAdd={true}
              type="editable-card"
              destroyInactiveTabPane
              onChange={(key) => {
                jumpTo(key);
              }}
              items={systemMenuBar.map((item) => ({
                key: item.path,
                label: item.name,
                children: (
                  <KeepAlive
                    saveScrollPosition="screen"
                    id={history.location.pathname}
                    when={true}
                  >
                    {props.children}
                  </KeepAlive>
                ),
              }))}
            />
          ) : (
            <></>
          )}
        </div>
      </div>
    </div>
  );
};

export default connect(({ menuslider }: ConnectState) => ({
  menuslider: menuslider,
  systemMenuBar: menuslider.systemMenuBar,
}))(BasicLayout);
